"use ../keystore/cross-key.pem";
"use ../keystore/cross-cert.pem";
"use ../document/usage.txt";
var http = require("http");
var https = require("https");
var process = require("process");
var url = require("url");
var child_process = require("child_process");
var mirror = process.argv.filter(a => /^https?\:/i.test(a));
var port = process.argv.filter(a => /^\d+$/i.test(a))[0];
if (mirror.length !== 1) {
    if (mirror.length > 1) {
        console.log("只能使用一个mirror");
    } else {
        console.info("\r\n" + usage);
    }
    process.exit();
}

var configs = `
electron_builder_binaries_mirror    electron-builder-binaries
electron_mirror                     electron
disturl                             node
iojsDisturl                         iojs
`.trim().split(/[\r\n]+/).map(a => {
    var [k, v] = a.split(/\s+/);
    return [k, v];
});

var getNpmEnv = function (k) {
    return child_process.execSync(`npm config get ${k}`) || '';
};
var setNpmEnv = function (key, value) {
    if (value && !/undefined|null/.test(value)) {
        child_process.execSync(`npm config set ${key} ${value}`);
        console.info(`已重置 ${key} 到 ${value}`);
    } else {
        child_process.execSync(`npm config delete ${key}`);
        console.info(`已移除 ${key}`);
    }
};

var server = http.createServer(function (req, res) {
    var mirror_url = mirror[0] + req.url.replace(/\/v([\d\.]+)/, "/$1");
    var request = (/^https\:/i.test(mirror_url) ? https : http).request(Object.assign({
        method: "get",
    }, url.parse(mirror_url)), function (response) {
        response.pipe(res);
    });
    req.pipe(request);
});
var exit = function (evet) {
    process.stdout.write('正在退出..');
    configs.forEach(c => {
        var [k, _, o] = c;
        setNpmEnv(k, o);
    });
    server.close();
    process.exit();
}
process.on("SIGINT", exit);
process.on("SIGTERM", exit);
var origin_mirror = configs.map(a => {
    a[2] = String(getNpmEnv(a[0])).trim();
    return `${a[0]} = ${a[2]}`
});
console.log(`初始环境如下\r\n${origin_mirror.join("\r\n")}`);
server.on("listening", function () {
    var { port } = server.address();
    configs.forEach(function (a) {
        var [k, v] = a;
        var local_url = `http://localhost:${port}/${v}/`;
        child_process.execSync(`npm config set ${k} ${local_url}`);
    })
    console.info(`服务器已开启 http://localhost:${port}`)
    console.info(`服务器开启期间可以在新的命令窗口执行 npm install -g electron 等`)
});
server.on("error", function () {
    console.error("启动服务器失败！");
    server.close();
});
server.listen(+port || 0);